/*
 * DirtyLogHelper.java
 *
 */

package pl.edu.pw.mini;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 *
 * @author cdendek
 */
public class DirtyLogHelper {
    
    /** Creates a new instance of DirtyLogHelper */
    public DirtyLogHelper() {
    }
    
    private static File file;
    static{
        try{
        file=File.createTempFile("OOIntPluginLog",".log");
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
    public static void main(String []args){
        append("UUU");
    }
    
    private static String getCurrTime(){
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss:SSS");
        java.util.Date date = new java.util.Date();
        return dateFormat.format(date);
    }
    
    private static String generateProlog(){
        String prolog="["+getCurrTime()+"]  ";
        Exception ex=new Exception();
        StackTraceElement[] ste=ex.getStackTrace();
        int i=0;
        for(;i<ste.length;i++){
            if (ste[i].getMethodName().indexOf("append")!=-1){
                break;
            }
        }
        i++;
        if (i<ste.length){
            prolog+="["+ste[i].getClassName()+"::"+ste[i].getMethodName()+"("+ste[i].getLineNumber()+")] ";
        }
        return prolog;
    }
    
    public static void append(Throwable t){
        try{
            File f=file;
            FileOutputStream fos=new FileOutputStream(f,true);
            PrintWriter pw=new PrintWriter(fos);
            pw.print(generateProlog());
            if (t.getMessage()!=null){
                pw.println(t.getMessage());
            }
            pw.println(t.toString());
            t.printStackTrace(pw);
            pw.flush();
            pw.close();
            fos.close();
        } catch(Exception exc){
            exc.printStackTrace();
        }
        
    }
    
    public static void append(String str){
        try{
            File f=file;
            FileOutputStream fos=new FileOutputStream(f,true);
            PrintWriter pw=new PrintWriter(fos);
            pw.print(generateProlog());
            pw.println(str);
            pw.flush();
            pw.close();
            fos.close();
        } catch(Exception ex){
            ex.printStackTrace();
        }
    }
    
}
